package com.wfh.activity;

import com.wfh.R;
import com.wfh.R.layout;
import com.wfh.R.menu;
import com.wfh.util.MyDialog;
import com.wfh.util.Util;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class FindPasswordActivity extends CommonActivity {
	final String numberpattern = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
	private boolean mBound = true;
	private Button submit;
	private MyDialog dialog;
	private EditText account;
	private BroadcastReceiver datareceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, R.layout.activity_findpasword);
		
		account = (EditText) findViewById(R.id.editText1);
		submit = (Button) findViewById(R.id.button1);
		dialog = MyDialog.create(this);

		// 注册recevier广播接收器
		IntentFilter filter = new IntentFilter();
		filter.addAction(Util.D_FINDPASSWORD);
		datareceiver = new DataReceiver();
		registerReceiver(datareceiver, filter);

		submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String accountstr = account.getText().toString();
				if (!Util.isexist(numberpattern, accountstr)) {
					Util.showToast(FindPasswordActivity.this, "必须输入正确手机号码");
					return;
				}

				Bundle bd = new Bundle();
				bd.putString("account", accountstr);
				if (mBound == false)
					return;
				HomeActivity.service.findPassword(FindPasswordActivity.this,
						new Intent().putExtras(bd));
				mBound = false;
				dialog.show();
			}
		});

	}

	// 接收器
	private class DataReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			dialog.hide();
			Bundle bd = intent.getExtras();
			mBound = true;
			if(bd==null){
				Util.showToast(FindPasswordActivity.this, "网络错误");
				return;
			}
			if (bd.getString("ret") == null) {
				Util.showToast(FindPasswordActivity.this, "出错了");
				return;
			} else if (bd.getString("ret").equals("1")) {
				Util.showToast(FindPasswordActivity.this, "成功(2分钟之内发送短信找回)");
				return;
			} else if (bd.getString("ret").equals("100")) {
				Util.showToast(FindPasswordActivity.this, "此用户不存在");
				return;
			} else if (bd.getString("ret").equals("101")) {
				Util.showToast(FindPasswordActivity.this, "当天找回已经超过三次");
				return;
			}
		}
	}

	@Override
	protected void onDestroy() {
		if (dialog != null)
			dialog.cancel();
		if (datareceiver != null)
			unregisterReceiver(datareceiver);
		super.onDestroy();
	}

}
